﻿using System.Windows;
using System.Windows.Media.Animation;

namespace Greycastle.RUBuildin.View
{
    /// <summary>Popup window showing build status</summary>
    public partial class BubbleWindow
    {
        private readonly Storyboard _closeStoryboard;
        private bool _closeStoryboardCompleted;

        /// <summary>Instantiates the bubble window</summary>
        public BubbleWindow()
        {
            AssemblyResolver.EnableResolutionFromManifestFolder();

            InitializeComponent();

            Loaded += OnLoaded;
            SizeChanged += OnSizeChanged;

            _closeStoryboard = (Storyboard)FindResource("CloseStoryboard");
            _closeStoryboard.Completed += (s, e) =>
                {
                    _closeStoryboardCompleted = true;
                    Close();
                };
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (_closeStoryboardCompleted)
                return;
            
            _closeStoryboard.Begin();
            e.Cancel = true;
        }

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            Reposition();
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Reposition();
        }

        private void Reposition()
        {
            var desktopWorkingArea = SystemParameters.WorkArea;
            Left = desktopWorkingArea.Right - Width - 40;
            Top = desktopWorkingArea.Bottom - Height - 40;
        }
    }
}
